package com.program.houai.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.program.houai.entity.UserEntity;
import com.program.houai.service.IUserService;
import com.program.houai.util.AliSmsUtil;
import com.program.houai.util.R;
import com.program.houai.util.SystemConstant;
import com.program.houai.vo.SmsCodeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @version v1.0
 * @ProjectName: EOrder-master
 * @ClassName: SmsCodeController
 * @Description: TODO(一句话描述该类的功能)
 * @Author: Topcheer
 * @Date: 2024/8/29 8:54
 */
@Api(tags = "验证码相关接口")
@RestController
@RequestMapping("/app/sms")
@Slf4j
@Validated
public class SmsCodeController {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private IUserService userService;

    @ApiOperation("发送短信验证码 4")
    @PostMapping(value = "/generateSmsCode", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<String> generateSmsCode(@RequestBody @Valid SmsCodeVO sysCodeVO) {
        Random random = new Random();
        // 生成一个三位数的随机数（100到999之间）
        String smsCode = 100000 + random.nextInt(900000)+"";
        Map map = new HashMap<>(4);
        map.put("code",smsCode);
        log.info("输出验证码========================================"+smsCode);
        // 对象转json
        JSONObject jsonObject = JSONObject.fromObject(map);

        AliSmsUtil aliSmsUtil = new AliSmsUtil();
        String  value = (String) redisTemplate.opsForValue().get(SystemConstant.PHONESMSCODE_TOKEN_KEY + sysCodeVO.getPhone());
        if (!StringUtils.isBlank(value)){
            return R.failed("请勿频繁请求验证码！！！");
        }
        // 发送短信
        SendSmsResponse sendSmsResponse = aliSmsUtil.sendSms(sysCodeVO.getPhone(),jsonObject,SystemConstant.SMS_162731973);
        if("OK".equals(sendSmsResponse.getCode())){
            redisTemplate.opsForValue().set(SystemConstant.PHONESMSCODE_TOKEN_KEY + sysCodeVO.getPhone(), smsCode, SystemConstant.PHONESMSCODE_TIMEOUT, TimeUnit.MINUTES);
        }else{
            return R.failed(sendSmsResponse.getMessage());
        }
        redisTemplate.opsForValue().set(SystemConstant.PHONESMSCODE_TOKEN_KEY + sysCodeVO.getPhone(), smsCode, SystemConstant.PHONESMSCODE_TIMEOUT, TimeUnit.MINUTES);
        return R.ok(smsCode,SystemConstant.PHONESMSCODE_TIMEOUT+"分钟之内有效");
    }

    @ApiOperation("校验注册短信验证码与手机号是否已存在")
    @PostMapping(value = "/checkSmsCode", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<String> checkSmsCode(@RequestBody @Valid SmsCodeVO sysCodeVO) {
        QueryWrapper<UserEntity> wrap = new QueryWrapper<UserEntity>();
        wrap.eq("phone",sysCodeVO.getPhone());
        UserEntity user = userService.getOne(wrap);
        if (user != null ){
            return R.failed("该手机号码已注册！！！");
        }
        String  value = (String) redisTemplate.opsForValue().get(SystemConstant.PHONESMSCODE_TOKEN_KEY + sysCodeVO.getPhone());
        if (StringUtils.isBlank(value)){
            return R.failed("验证码无效或已过期");
        }else{
            if (!value.equals(sysCodeVO.getCode())){
                return R.failed("验证码输入错误！！！");
            }
        }
        redisTemplate.delete(SystemConstant.PHONESMSCODE_TOKEN_KEY + sysCodeVO.getPhone());
        return R.ok();
    }

    @ApiOperation("分享注册验证校验")
    @PostMapping(value = "/h5CheckSmsCode", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<String> h5CheckSmsCode(@RequestBody @Valid SmsCodeVO sysCodeVO) {
        String  value = (String) redisTemplate.opsForValue().get(SystemConstant.PHONESMSCODE_TOKEN_KEY + sysCodeVO.getPhone());
        if (StringUtils.isBlank(value)){
            return R.failed("验证码无效或已过期");
        }else{
            if (!value.equals(sysCodeVO.getCode())){
                return R.failed("验证码输入错误！！！");
            }
        }
        redisTemplate.delete(SystemConstant.PHONESMSCODE_TOKEN_KEY + sysCodeVO.getPhone());
        return R.ok();
    }


}
